package cn.edu.jxust.controller.api.device;

import cn.edu.jxust.common.domain.entity.Device;
import cn.edu.jxust.common.domain.dto.DeviceSiteVo;
import cn.edu.jxust.common.domain.valobj.DeviceVo;
import cn.edu.jxust.common.domain.dto.RegDeviceVo;
import cn.edu.jxust.common.domain.web.api.device.IDeviceController;
import cn.edu.jxust.common.response.Result;
import cn.edu.jxust.common.response.ResultUtils;
import cn.edu.jxust.common.response.enums.ResultStatus;
import cn.edu.jxust.core.domain.repository.DeviceService;
import cn.edu.jxust.core.domain.repository.SiteService;
import cn.edu.jxust.core.infrastructure.util.Const;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuguangyun
 * @since 2020-06-30
 *
 * @description 设备管理相关接口:
 *      权限说明: 超级管理员可查询所有区域所有企业部署的设备信息
 *              局级管理员和超级管理员一样
 *              区级管理员只能查询指定区域的设备信息(根据管理员的 area_id 来查)
 *              企业用户只能插叙你自己企业部署的设备信息 (根据企业用户的 enterprise_id 来查)
 *
 */
@Slf4j
@RestController
public class DeviceController implements IDeviceController {

    @Resource
    private DeviceService deviceService;
    @Resource
    private SiteService siteService;

    @Override
    public Result getOneDevice(Integer id){

        try{
            return deviceService.getOneById(id);
        }catch (Exception e){
            log.error("DeviceController --> getOneDevice: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result getDeviceList(Integer page, Integer size, HttpServletRequest request){

        try{
            Map<String, String[]> paramMap = new HashMap<>(request.getParameterMap());
            return deviceService.getDeviceVoListOrQuery(paramMap, page, size);
        }catch (Exception e){
            log.error("[DeviceController --> getDeviceList]: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result delOneDevice(Integer id) {

        try{
            return deviceService.delById(id);
        }catch (Exception e){
            log.error("DeviceController --> delOneDevice: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result addOneDevice(DeviceVo deviceVo, BindingResult result){

        if(result.hasErrors() || null == deviceVo.getCreateUserid()){
            return ResultUtils.resultWithoutData(ResultStatus.PARAM_ERROR);
        }
        try {
            return deviceService.addDevice(deviceVo);
        } catch (Exception e) {
            log.error("[DeviceController --> adOneDevice]: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result updateDevice(DeviceVo deviceVo, BindingResult result){

        if(result.hasErrors() || null == deviceVo.getId()){
            return ResultUtils.resultWithoutData(ResultStatus.PARAM_ERROR);
        }
        try{
            return deviceService.modifyDevice(deviceVo);
        } catch (Exception e) {
            log.error("DeviceController --> updateDevice: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result getNoBinding(Integer page, Integer size){

        try{
            IPage<DeviceVo> list = deviceService.getNoBindingList(page, size);
            if(list.getRecords() != null && !list.getRecords().isEmpty()){
                return ResultUtils.resultWithData(ResultStatus.SUCCESS, list);
            }else {
                return ResultUtils.resultWithoutData(ResultStatus.NOT_FOUND, "未找到未绑定监测点的设备");
            }
        }catch (Exception e){
            log.error("DeviceController --> getNoBinding: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result binding(DeviceSiteVo deviceSiteVo, BindingResult result) {

        if(result.hasErrors()){
            return ResultUtils.resultWithoutData(ResultStatus.PARAM_ERROR);
        }
        try{
            if(deviceSiteVo.getIsBinding().equals(Const.BINDING)){
                //设备绑定监测点操作

                //判断设备是否绑定
                if(deviceService.deviceIsBinding(deviceSiteVo.getDeviceId())){
                    //已经绑定了
//                    log.error("该设备已绑定监测点, 请更换设备或先解绑!");
                    return ResultUtils.resultWithoutData(ResultStatus.FAILED, "该设备已绑定监测点, 请更换设备或先解绑!");
                }

                //判断监测点是否绑定
                if(siteService.siteIsBinding(deviceSiteVo.getSiteId())){
                    //监测点已经绑定了设备
//                    log.error("该监测点已经绑定了监测设备, 请更换监测点或先解绑该监测点!");
                    return ResultUtils.resultWithoutData(ResultStatus.FAILED, "该监测点已经绑定了监测设备, 请更换监测点或先解绑该监测点!");
                }

            }else if(deviceSiteVo.getIsBinding().equals(Const.NOT_BINDING)){
                //设备解绑监测点操作

                //判断设备是否绑定
                if(!deviceService.deviceIsBinding(deviceSiteVo.getDeviceId())){
                    //设备没有绑定监测点
//                    log.error("该设备未绑定监测点, 请查验正确!");
                    return ResultUtils.resultWithoutData(ResultStatus.FAILED, "该设备未绑定监测点, 请查验正确!");
                }

                //判断监测点是否绑定
                if(!siteService.siteIsBinding(deviceSiteVo.getSiteId())){
                    //监测点没有绑定设备
//                    log.error("该监测点没有绑定监测设备, 请查验正确!");
                    return ResultUtils.resultWithoutData(ResultStatus.FAILED, "该监测点没有绑定监测设备, 请查验正确!");
                }

                //绑定了监测点, 判断绑定的监测点的id是否正确
                if(!deviceSiteVo.getSiteId().equals(deviceService.getSiteIdById(deviceSiteVo.getDeviceId()))){
                    //并没有绑定该监测点
//                    log.error("此设备未绑定该监测点, 请查验正确!");
                    return ResultUtils.resultWithoutData(ResultStatus.FAILED, "此设备未绑定该监测点, 请查验正确!");
                }
            }

            String msg = deviceSiteVo.getIsBinding().equals(Const.NOT_BINDING) ? "解绑" : "绑定";
            return deviceService.deviceBindingOr(deviceSiteVo)
                    ? ResultUtils.resultWithoutData(ResultStatus.SUCCESS, "设备" + msg + "监测点成功")
                    : ResultUtils.resultWithoutData(ResultStatus.FAILED, "设备" + msg + "监测点失败");
        }catch (Exception e){
            log.error("DeviceController --> binding: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result getEnterpriseListByAreaIdAndId(Integer areaId, Integer enterpriseId){

        try{
            List<Device> list = deviceService.getDeviceByAreaIdAndId(areaId, enterpriseId);
            if(null != list && list.size() != 0){
                return ResultUtils.resultWithData(ResultStatus.SUCCESS, list);
            }else{
                return ResultUtils.resultWithoutData(ResultStatus.NOT_FOUND, "未找到任何有关企业信息");
            }
        }catch (Exception e){
            log.error("DeviceController --> getEnterpriseListByAreaIdAndId:{} ", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result getWaitDeviceList(Integer page, Integer size){

        try{
            IPage<RegDeviceVo> deviceVoPage = deviceService.getRegDeviceVoList(page, size, Const.NEW_DEVICE);
            if(deviceVoPage.getRecords() != null && !deviceVoPage.getRecords().isEmpty()){
                return ResultUtils.resultWithData(ResultStatus.SUCCESS, deviceVoPage);
            }else{
                return ResultUtils.resultWithoutData(ResultStatus.NOT_FOUND, "当前未找到任何待处理设备");
            }
        }catch (Exception e){
            log.error("DeviceController --> getWaitDeviceList: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result doWait(DeviceVo deviceVo, BindingResult result){

        if(result.hasErrors() || null == deviceVo.getId()){
            return ResultUtils.resultWithoutData(ResultStatus.PARAM_ERROR);
        }
        try{
            return deviceService.doWait(deviceVo);
        }catch (Exception e){
            log.error("DeviceController --> getWaitDeviceList: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

    @Override
    public Result getDefaultDeviceId(){

        try{
            Integer defaultDeviceId = deviceService.getDefaultDeviceId();
            if(defaultDeviceId != null){
                return ResultUtils.resultWithData(ResultStatus.SUCCESS, defaultDeviceId);
            }else{
                return ResultUtils.resultWithoutData(ResultStatus.FAILED, "无任何设备输入信息,请添加或将设备绑定监测点?");
            }
        }catch (Exception e){
            log.error("DeviceController --> getDefaultDeviceId: {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }
    }

}